import Audio from "../lib/Audio";
import { useState, useRef, useEffect } from "react";
function useAudio(src?: string) {
  const [isPlaying, setIsPlaying] = useState(false);
  const audio = useRef(new Audio(src));
  const [duration, setDuration] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);

  function onPlay() {
    setIsPlaying(true);
  }

  function onPause() {
    setIsPlaying(false);
  }

  function onTimeupdate() {
    setCurrentTime(audio.current.currentTime);
  }

  function updateCurrentTime(time: number) {
    setCurrentTime(time);
    audio.current.currentTime = time;
  }

  function onCanplay() {
    setDuration(audio.current.duration);
  }

  function initEvent() {
    audio.current.addEventListener("canplay", onCanplay);
    audio.current.addEventListener("play", onPlay);
    audio.current.addEventListener("pause", onPause);
    audio.current.addEventListener("timeupdate", onTimeupdate);
  }

  function removeEvent() {
    audio.current.removeEventListener("play", onPlay);
    audio.current.removeEventListener("pause", onPause);
    audio.current.removeEventListener("timeupdate", onTimeupdate);
  }

  function play() {
    audio.current.play();
  }

  function pause() {
    audio.current.pause();
  }

  useEffect(() => {
    initEvent();
    return () => {
      removeEvent();
    };
  }, []);

  useEffect(() => {
    if (src) {
      audio.current.src = src;
    }
  }, [src]);

  return {
    audio,
    isPlaying,
    play,
    pause,
    duration,
    currentTime,
    updateCurrentTime,
  };
}

export default useAudio;
